package com.yh.csx.crm.service;

import com.yh.csx.crm.dao.SysCustomerCategoryMapper;
import com.yh.csx.crm.po.SysCustomerCategory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author Huang Zhaoping
 * @date 2019/3/12
 */
@Service
public class CategoryService {

    @Autowired
    private SysCustomerCategoryMapper categoryMapper;

    @Autowired
    private CacheService cacheService;

    public List<SysCustomerCategory> getCategoryList() {
        return cacheService.getValue("CategoryService.getCategoryList", 3600000, () -> categoryMapper.selectAllList());
    }

    public SysCustomerCategory getCategory(String parent, String code) {
        Optional<SysCustomerCategory> optional = getCategoryList().stream().filter(c -> Objects.equals(parent, c.getParentCode()) && Objects.equals(code, c.getCategoryCode())).findFirst();
        return optional.isPresent() ? optional.get() : null;
    }

    public String getCategoryName(String parent, String code) {
        SysCustomerCategory category = getCategory(parent, code);
        return category == null ? null : category.getCategoryName();
    }

    public String getCategoryFullName(String parent, String code) {
        String[] codes = {"0", parent, code};
        String parentName = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < codes.length; i++) {
            String nodeName = getCategoryName(codes[i - 1], codes[i]);
            if (StringUtils.isBlank(nodeName)) continue;
            if (parentName != null && StringUtils.equals(parentName, nodeName)) {
                continue;
            }
            if (sb.length() > 0) sb.append(" - ");
            sb.append(nodeName);
            parentName = nodeName;
        }
        return sb.toString();
    }
}
